import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'

// 路由懒加载,按需导入
const Layout = () => {
  return import('@/views/Layout')
}

// 商品的界面
const Home = () => {
  return import('@/views/home/index')
}
const TopCategory = () => {
  return import('@/views/category/index.vue')
}
const SubCategory = () => {
  return import('@/views/category/sub.vue')
}
const Goods = () => {
  return import('@/views/goods/index.vue')
}
// 购物车详情页面
const Cart = () => {
  return import('@/views/cart/index.vue')
}
// 结算支付页面
const checkOut = () => {
  return import('@/views/member/pay/checkout.vue')
}
// 支付页面
const PayIndex = () => {
  return import('@/views/member/pay/index.vue')
}

const Login = () => {
  return import('@/views/login/index.vue')
}
const LoginCallback = () => {
  return import('@/views/login/login-callback.vue')
}

// 路由规则
const routes = [
  // 一级路由布局容器
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home
      },
      {
        // 携带的是params参数
        path: 'category/:id',
        component: TopCategory
      },
      {
        path: 'category/sub/:id',
        component: SubCategory
      },
      {
        path: 'product/:id',
        component: Goods
      },
      { path: 'cart', component: Cart },
      { path: '/member/checkout', component: checkOut },
      { path: '/member/pay', component: PayIndex }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/login/callback',
    component: LoginCallback
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  // 如果没有登录就是没有token  而且登录页面都是/member  开头的都要拦截   怎么拿到token
  const { profile } = store.state.user
  if (!profile.token && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
